package com.ffsky.cordova.plugin;

import android.app.Activity;
import android.app.Dialog;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ffsky.cordova.app.WebActivity;
import com.ffsky.cordova.option.WebOption;
import com.ffsky.cordova.util.ColorCompat;
import com.ffsky.cordova.util.JSONCompat;
import com.ffsky.jsplugin.JsCallback;
import com.ffsky.jsplugin.JsPlugin;
import com.ffsky.litepack.Lite;
import com.ffsky.litepack.dialog.OnPositiveListener;
import com.ffsky.litepack.dialog.PromptDialog;
import com.ffsky.litepack.toolbar.Toolbar;
import com.ffsky.litepack.util.ActivityUtil;
import com.ffsky.logger.L;

/**
 * page页面插件,vue调用page插件，打开新页面
 */
public class PageJsPlugin extends JsPlugin {
    private Toolbar toolbar;
    private WebActivity mWebActivity;

    @Override
    public void onCreate(Activity activity) {
        super.onCreate(activity);
        if (activity instanceof WebActivity) {
            mWebActivity = (WebActivity) activity;
            toolbar = mWebActivity.getToolbar();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        toolbar = null;
        mWebActivity = null;
    }

    /**
     * 显示提示框
     *
     * @param title
     * @param msg
     * @param ok
     * @param cancel
     * @param okJsCall
     * @param cancelJsCall
     */
    @JavascriptInterface
    public void showDialog(String title, String msg, String ok, String cancel, String okJsCall, String cancelJsCall) {
        L.i(TAG, "showDialog->title=",title," msg=",msg,
                " ok=",ok," cancel=",cancel," okJsCall=",okJsCall," cancelJsCall=",cancelJsCall);
        Activity activity = getActivity();
        if(activity!=null){
            PromptDialog dialog = new PromptDialog(getActivity());
            dialog.setTitle(title);
            dialog.setContentText(msg);
            if(!TextUtils.isEmpty(ok)){
                final JsCallback jsCallback = buildJsCallback();
                final String jsCall = okJsCall;
                dialog.setPositiveListener(ok, new OnPositiveListener() {
                    @Override
                    public void onClick(Dialog _dialog) {
                        if(!TextUtils.isEmpty(jsCall) && jsCallback!=null){
                            jsCallback.applyMethodName(jsCall,null);
                        }
                        _dialog.dismiss();
                    }
                });
            }
            if(!TextUtils.isEmpty(cancel)){
                final JsCallback jsCallback = buildJsCallback();
                final String jsCall = cancelJsCall;
                dialog.setNegativeListener(cancel, new OnPositiveListener() {
                    @Override
                    public void onClick(Dialog _dialog) {
                        if(!TextUtils.isEmpty(jsCall) && jsCallback!=null){
                            jsCallback.applyMethodName(jsCall,null);
                        }
                        _dialog.dismiss();
                    }
                });
            }
            //
            dialog.setCancelable(false);
            dialog.show();
        }
    }

    @JavascriptInterface
    public void clearHistory() {
        L.i(TAG, "clearHistory");
        if (mWebActivity != null) {
            mWebActivity.clearHistory();
        }
    }

    @JavascriptInterface
    public String getData() {
        L.i(TAG, "getData");
        if (mWebActivity != null) {
            String pageData = mWebActivity.getPageData();
            return pageData;
        } else {
            JSONObject json = new JSONObject();
            return json.toJSONString();
        }
    }

    @JavascriptInterface
    public void setOnBackListener(String jsCallName) {
        L.i(TAG, "setOnBackListener->", jsCallName);
        if (mWebActivity != null) {
            mWebActivity.setOnBackListener(jsCallName);
        }
    }

    @JavascriptInterface
    public void setOnLongBackListener(String jsCallName) {
        L.i(TAG, "setOnLongBackListener->", jsCallName);
        if (mWebActivity != null) {
            mWebActivity.setOnLongBackListener(jsCallName);
        }
    }

    /**
     * 打开一个新的WebActivity页面
     *
     * @param url      网址
     * @param backMode 1=原路返回,2=返回页面第一个url地址,3=WebView页面销毁
     */
    @JavascriptInterface
    public void openPage(String url, int backMode) {
        L.i(TAG, "openPage->", url);
        WebActivity.start(getActivity(), url, backMode, null);
    }

    /**
     * 打开一个新的WebActivity页面
     *
     * @param url        网址
     * @param backMode   1=原路返回,2=返回页面第一个url地址,3=WebView页面销毁
     * @param jsonOption 页面参数 {"showStatusBar":true,"showToolBar":true,"statusBarColor":"","toolbarColor":""
     *                   ,title":"",updateTitle":false}
     */
    @JavascriptInterface
    public void openPage(String url, int backMode, String jsonOption) {
        L.i(TAG, "openPage->", url);
        if (!TextUtils.isEmpty(jsonOption)) {
            try {
                JSONObject opt = JSON.parseObject(jsonOption);
                if (opt != null) {
                    WebOption webOption = new WebOption(url);
                    webOption.backMode = backMode;
                    webOption.showStatusBar = JSONCompat.readBoolean("showStatusBar", opt, true);
                    webOption.showToolBar = JSONCompat.readBoolean("showToolBar", opt, true);
                    String statusBarColor = JSONCompat.readString("statusBarColor", opt);
                    String toolbarColor = JSONCompat.readString("toolbarColor", opt);
                    //
                    webOption.statusBarColor = ColorCompat.parseColor(statusBarColor, 0);
                    webOption.toolbarColor = ColorCompat.parseColor(toolbarColor, 0);
                    //
                    webOption.title = JSONCompat.readString("title", opt);
                    webOption.updateTitle = JSONCompat.readBoolean("updateTitle", opt, true);
                    //
                    WebActivity.startOption(getActivity(), webOption);
                } else {
                    WebActivity.start(getActivity(), url, backMode, null);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                WebActivity.start(getActivity(), url, backMode, null);
            }
        } else {
            WebActivity.start(getActivity(), url, backMode, null);
        }
    }

    @JavascriptInterface
    public void setGoBackUrl(String url) {
        L.i(TAG, "setGoBackUrl->", url);
        if (mWebActivity != null) {
            mWebActivity.setGoBackUrl(url);
        }

    }

    @Override
    public void onPageFinished() {
        L.i(TAG, "onPageFinished");
        super.onPageFinished();
        if (enableClearHistory) {
            enableClearHistory = false;
            Activity activity = getActivity();
            if (activity instanceof WebActivity) {
                WebActivity webActivity = (WebActivity) activity;
                webActivity.clearHistory();
            }
        }
    }

    /**
     * 关闭一个WebActivity页面
     */
    @JavascriptInterface
    public void closePage() {
        L.i(TAG, "closePage");
        Activity aty = getActivity();
        if (!ActivityUtil.isDestroyed(aty)) {
            aty.finish();
        }
    }

    private boolean enableClearHistory;

    /**
     * 在当前WebActivity页面从新加载新的url地址
     *
     * @param url          网址
     * @param clearHistory url加载成功后是否清除WebView clearHistory
     */
    @JavascriptInterface
    public void loadPage(String url, boolean clearHistory) {
        L.i(TAG, "loadPage");
        Activity activity = getActivity();
        if (activity instanceof WebActivity) {
            WebActivity webActivity = (WebActivity) activity;
            enableClearHistory = clearHistory;
            webActivity.loadUrl(url);
        }
    }

    /**
     * 设置当前WebActivity Title
     *
     * @param title 标题
     */
    @JavascriptInterface
    public void setTitle(final String title) {
        L.i(TAG, "setTitle");
        final String newTitle = String.valueOf(title);
        Lite.task.ui(new Runnable() {
            @Override
            public void run() {
                if (toolbar != null) {
                    toolbar.setTitle(newTitle);
                }
            }
        });
    }

    /**
     * 强制返回首页，关闭二级页面一下所有页面
     */
    @JavascriptInterface
    public void goHome() {
        L.i(TAG, "goHome");
        Lite.appInterface.goAppHome(true);
    }

    /**
     * 关闭app
     */
    @JavascriptInterface
    public void exitApp() {
        L.i(TAG, "exitApp");
        Lite.appInterface.closeApp();
    }


}
